<?php
/**
 * Created by IntelliJ IDEA.
 * User: iqny
 * Date: 2019-01-30
 * Time: 14:52
 */

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use App\Models\Authorization;
use App\Transformers\AuthorizationTransformer;
use App\Transformers\UserTransformer;

class AuthController extends BaseController
{
    /**
     *
     * @param Request $request
     * @return \Dingo\Api\Http\Response|\Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);
        if ($validator->fails()) {
            //throw new \Dingo\Api\Exception\StoreResourceFailedException('Could not create new user.', $validator->errors());
            return $this->errorBadRequest($validator);
        }
        $credentials = $request->only('email', 'password');
        if (!$token = \Auth::guard()->attempt($credentials)) {
            $this->response->errorUnauthorized();
        }
        $authorization = new Authorization($token);

        return $this->response->item($authorization, new AuthorizationTransformer())->setStatusCode(201);
        //return $this->respondWithToken($token);
    }

    /**
     *
     * @return \Dingo\Api\Http\Response
     */
    public function me()
    {
        return $this->response->item(\Auth::guard()->user(), new UserTransformer());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        \Auth::guard()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(\Auth::guard()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => \Auth::guard()->factory()->getTTL() * 60
        ]);
    }
}
